package org.jboss.netty.channel.socket.oio;

import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketAddress;

import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelSink;
import org.jboss.netty.channel.socket.SocketChannel;

import uqbar.comm.netty.ProgramException;

public class SerialClientSocketChannel extends OioClientSocketChannel implements SocketChannel {

	private CommPortIdentifier portIdentifier;
	private SerialPort serialPort;

	// TODO Esto podrian ser options
	/** Milliseconds to block while waiting for port open */
	private int timeOut = 2000;
	/** Default bits per second for COM port. */
	private int dataRate = 9600;
	private SocketAddress address;

	private boolean connected;

	SerialClientSocketChannel(final ChannelFactory factory, final ChannelPipeline pipeline, final ChannelSink sink) {
		super(factory, pipeline, sink);
	}

	public int getDataRate() {
		return this.dataRate;
	}

	public int getTimeOut() {
		return this.timeOut;
	}

	public CommPortIdentifier getPortIdentifier() {
		return this.portIdentifier;
	}

	public InputStream createInputStream() {
		try {
			return this.serialPort.getInputStream();
		} catch (IOException e) {
			throw ProgramException.wrap(e);
		}
	}

	public OutputStream createOutpurStream() {
		try {
			return this.serialPort.getOutputStream();
		} catch (IOException e) {
			throw ProgramException.wrap(e);
		}
	}

	public void setAddress(final SocketAddress address) {
		this.address = address;
	}

	public SocketAddress getAddress() {
		return this.address;
	}

	public void setPortIdentifier(final CommPortIdentifier portIdentifier) {
		this.portIdentifier = portIdentifier;
	}

	public void setSerialPort(final SerialPort port) {
		this.serialPort = port;
	}

	public SerialPort getSerialPort() {
		return this.serialPort;
	}

	@Override
	public boolean isConnected() {
		return this.connected;
	}

	@Override
	public boolean isOpen() {
		return this.connected;
	}

	public void setConnected(final boolean connected) {
		this.connected = connected;
	}

}
